<template>
	<view class="form-section">
		<view class="section-title">填写模块：</view>
		<image class="imgBox" mode="aspectFill" src="https://www.pengfei.site:8443/image/flower.gif"></image>
		<view class="form-content">
			<view class="form-item">
				<text class="label">报修人：</text>
				<input class="input-field" v-model="formData.reporter" placeholder="请输入报修人姓名" />
			</view>

			<view class="form-item">
				<text class="label">报修院系：</text>
				<picker @change="onDepartmentChange" :value="departmentIndex" :range="departments">
					<view class="picker-view">
						<text>{{ formData.department || '请选择学院/部门' }}</text>
						<uni-icons class="arrow" type="down"></uni-icons>
					</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="label">周次：</text>
				<input class="input-field" v-model="formData.week" placeholder="请输入周次，只需要数字" />
			</view>

			<view class="form-item">
				<text class="label">处理人：</text>
				<input class="input-field" v-model="formData.handler" placeholder="请输入处理人姓名" />
			</view>

			<view class="form-item">
				<text class="label">报修时间：</text>
				<view class="date-picker" @click="showRepairDatePicker = true">
					<text>{{ formData.repairTime || '请选择报修时间' }}</text>
					<uni-icons class="arrow" type="down"></uni-icons>
				</view>
			</view>

			<view class="form-item">
				<text class="label">故障教室/书院：</text>
				<input class="input-field" v-model="formData.faultLocation" placeholder="例如：勤者楼301或綦河书院3104" />
			</view>

			<view class="form-item">
				<text class="label">是否为外聘教师：</text>
				<radio-group @change="onExternalTeacherChange">
					<label class="radio-item radio-item-first">
						<radio value="是" :checked="formData.isExternalTeacher === '是'" />
						<text>是</text>
					</label>
					<label class="radio-item">
						<radio value="否" :checked="formData.isExternalTeacher === '否'" />
						<text>否</text>
					</label>
				</radio-group>
			</view>

			<view class="form-item">
				<text class="label">报修方式：</text>
				<picker @change="onRepairMethodChange" :value="repairMethodIndex" :range="repairMethods">
					<view class="picker-view">
						<text>{{ formData.repairMethod || '请选择报修方式' }}</text>
						<uni-icons class="arrow" type="down"></uni-icons>
					</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="label">报修类型：</text>
				<picker @change="onRepairTypeChange" :value="repairTypeIndex" :range="repairTypes">
					<view class="picker-view">
						<text>{{ formData.repairType || '请选择报修类型' }}</text>
						<uni-icons class="arrow" type="down"></uni-icons>
					</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="label">是否更换设备：</text>
				<radio-group @change="onEquipmentChangeChange">
					<label class="radio-item radio-item-first">
						<radio value="是" :checked="formData.isEquipmentChanged === '是'" />
						<text>是</text>
					</label>
					<label class="radio-item">
						<radio value="否" :checked="formData.isEquipmentChanged === '否'" />
						<text>否</text>
					</label>
				</radio-group>
			</view>

			<view class="form-item">
				<text class="label">处理情况：</text>
				<radio-group @change="onHandlingStatusChange">
					<label class="radio-item radio-item-first">
						<radio value="已处理" :checked="formData.handlingStatus === '已处理'" />
						<text>已处理</text>
					</label>
					<label class="radio-item">
						<radio value="未处理" :checked="formData.handlingStatus === '未处理'" />
						<text>未处理</text>
					</label>
				</radio-group>
			</view>

			<view class="form-item">
				<text class="label">故障发生原因：</text>
				<picker @change="onFormFaultReasonChange" :value="formFaultReasonIndex" :range="faultReasons">
					<view class="picker-view">
						<text>{{ formData.faultReasonType || '请选择故障发生原因' }}</text>
						<uni-icons class="arrow" type="down"></uni-icons>
					</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="label">处理方式、或未处理原因：</text>
				<textarea class="textarea-field" v-model="formData.faultReason"
					placeholder="请输入故障处理方式、或未处理原因(请按照如何处理+解决成功没)" :maxlength="200"></textarea>
			</view>
		</view>

		<button class="submit-btn" @click="handleSubmit">提交</button>

		<!-- 报修时间选择器弹窗 -->
		<view v-if="showRepairDatePicker" class="popup-overlay" @click="showRepairDatePicker = false">
			<view class="date-picker-popup" @click.stop>
				<view class="popup-header">
					<text class="cancel-btn" @click="showRepairDatePicker = false">取消</text>
					<text class="title">选择报修时间</text>
					<text class="confirm-btn" @click="confirmRepairDate">确定</text>
				</view>
				<picker-view class="picker-view" :value="repairDatePickerValue" @change="onRepairDatePickerChange">
					<picker-view-column>
						<view v-for="(item, index) in years" :key="index" class="picker-item">{{ item }}年</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item, index) in months" :key="index" class="picker-item">{{ item }}月</view>
					</picker-view-column>
					<picker-view-column>
						<view v-for="(item, index) in days" :key="index" class="picker-item">{{ item }}日</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	reactive,
	computed,
	onMounted
} from 'vue'
import { useUserStore } from '../../../stores/user'
import { repairAPI } from '../../../api/repair'

	const userStore = useUserStore()
	// 定义事件
	const emit = defineEmits(['submit'])

	// 表单数据
	const formData = reactive({
		// 报修人
		reporter: '',
		// 报修院系
		department: '',
		// 周次
		week: '',
		// 处理人
		handler: userStore.username,
		// 报修时间
		repairTime: '',
		// 故障教室/书院
		faultLocation: '',
		// 报修类型
		repairType: '',
		// 是否为外聘教师
		isExternalTeacher: '',
		// 报修方式
		repairMethod: '',
		// 是否更换设备
		isEquipmentChanged: '',
		// 处理情况
		handlingStatus: '',
		// 故障发生原因
		faultReasonType: '',
		// 故障详细描述
		faultReason: ''
	})

	// 选择器数据
	const departments = [
		'大健康管理学院',
		'通识教学部',
		'马克思主义学院',
		'数字经济商学院',
		'戏剧影视学院',
		'数理教学部',
		'大数据学院',
		'信息安全学院',
		'计算机学院',
		'外聘教师',
		'物理教研室',
		'国际教育学院（英语教研室）',
		'竞技体育中心',
		'瀛洲科幻学院',
		'电影评论中心',
		'电影商务产业学院',
		'创意写作学院',
		'地域文化与城市发展研究院',
		'酒店商务产业学院',
		'淬炼商学院',
		'通信与信息工程学院',
		'双体软件精英产业学院',
		'网络与信息管理中心',
		'新商科教学部',
		'艺术教育中心',
		'远景学院',
		'实训中心',
		'团委',
		'院领导',
		'人力资源处',
		'图书馆',
		'书院部',
		'学生处',
		'重点实验室',
		'基建后勤处',
		'剧本杀学院',
		'就业创业指导与服务中心/创业学院',
	]

	const repairTypes = [
		'教师',
		'话筒',
		'投影仪',
		'音响',
		'云桌面',
		'线路',
		'显示器',
		'多媒体柜',
		'电路，外设',
		'中控',
		'云终端',
		'幕布',
		'其他'
	]

	const repairMethods = ['电话报修', '多媒体群报修', '其他']

	// 故障发生原因选项
	const faultReasons = [
		'教师不会用',
		'教师将线路插错',
		'教师自行调整设备',
		'教师未规范使用',
		'教师导致设备故障',
		'教师要求新装软件',
		'话筒损坏',
		'话筒串音',
		'话筒噪音',
		'话筒无法匹配接收器',
		'话筒充电线损坏',
		'音响音量问题',
		'音响功放板故障',
		'音响噪音',
		'多媒体柜锁问题',
		'云桌面问题，重启可解决',
		'云桌面软件问题，需调整或重装软件',
		'线路掉落',
		'线路松动',
		'云终端故障',
		'空开跳闸',
		'电源线故障',
		'插线板故障',
		'显示器问题，微调可解决',
		'显示器故障，需更换显示器',
		'投影仪死机，重启可解决',
		'投影仪位置不正',
		'投影仪硬件故障，需维修投影仪',
		'投影仪问题，微调可解决',
		'中控线路问题',
		'中控死机，重启可解决',
		'中控硬件故障，需更换中控',
		'幕布',
		'键盘',
		'鼠标',
		'插头没有插好',
		'VGA线故障或接触不良',
		'网络问题',
		'其他'
	]

	const departmentIndex = ref(0)
	const repairTypeIndex = ref(0)
	const repairMethodIndex = ref(0)
	const formFaultReasonIndex = ref(0)
	const showRepairDatePicker = ref(false)

	// 日期选择器数据
	const currentDate = new Date()
	const years = Array.from({
		length: 10
	}, (_, i) => currentDate.getFullYear() - 5 + i)
	const months = Array.from({
		length: 12
	}, (_, i) => i + 1)
	const days = computed(() => {
		const year = years[repairDatePickerValue.value[0]]
		const month = months[repairDatePickerValue.value[1]]
		const daysInMonth = new Date(year, month, 0).getDate()
		return Array.from({
			length: daysInMonth
		}, (_, i) => i + 1)
	})

	const repairDatePickerValue = ref([5, currentDate.getMonth(), currentDate.getDate() - 1])

	// 初始化今天的日期和默认值
	const initTodayDate = () => {
		const today = new Date()
		const year = today.getFullYear()
		const month = (today.getMonth() + 1).toString().padStart(2, '0')
		const day = today.getDate().toString().padStart(2, '0')
		const todayStr = `${year}-${month}-${day}`

		// 设置报修时间默认值
		formData.repairTime = todayStr

		// 设置单选框默认值
		formData.isExternalTeacher = '否'
		formData.isEquipmentChanged = '否'
		formData.handlingStatus = '已处理'
	}

	// 日期选择器事件
	const onRepairDatePickerChange = (e) => {
		repairDatePickerValue.value = e.detail.value
	}

	const confirmRepairDate = () => {
		const year = years[repairDatePickerValue.value[0]]
		const month = months[repairDatePickerValue.value[1]]
		const day = days.value[repairDatePickerValue.value[2]]
		formData.repairTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
		showRepairDatePicker.value = false
	}

	// 选择器事件
	const onDepartmentChange = (e) => {
		departmentIndex.value = e.detail.value
		formData.department = departments[e.detail.value]
	}

	const onRepairTypeChange = (e) => {
		repairTypeIndex.value = e.detail.value
		formData.repairType = repairTypes[e.detail.value]
	}

	const onRepairMethodChange = (e) => {
		repairMethodIndex.value = e.detail.value
		formData.repairMethod = repairMethods[e.detail.value]
	}

	const onExternalTeacherChange = (e) => {
		formData.isExternalTeacher = e.detail.value
	}

	const onEquipmentChangeChange = (e) => {
		formData.isEquipmentChanged = e.detail.value
	}

	const onHandlingStatusChange = (e) => {
		formData.handlingStatus = e.detail.value
	}

	// 表单中故障发生原因选择器事件
	const onFormFaultReasonChange = (e) => {
		formFaultReasonIndex.value = e.detail.value
		formData.faultReasonType = faultReasons[e.detail.value]
	}

	// 提交功能
	const handleSubmit = async () => {
		// 检查登录状态
		if (!userStore.isAuthenticated) {
			uni.showModal({
				title: '需要登录',
				content: '提交表单需要先登录，是否前往登录页面？',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
			return
		}

		// 验证必填字段
		const requiredFields = ['reporter', 'department', 'week', 'handler', 'repairTime', 'faultLocation',
			'repairType', 'faultReasonType'
		]
		const missingFields = requiredFields.filter(field => !formData[field])

		if (missingFields.length > 0) {
			uni.showToast({
				title: '请填写所有必填字段',
				icon: 'none'
			})
			return
		}

		try {
			// 显示加载提示
			uni.showLoading({
				title: '提交中...'
			})

			// 转换数据格式以匹配API要求
			const apiData = {
				reporter: formData.reporter,
				department: formData.department,
				week: formData.week.startsWith('第') ? formData.week : `第${formData.week}周`,
				handler: formData.handler,
				repairTime: formData.repairTime,
				faultLocation: formData.faultLocation,
				repairType: formData.repairType,
				isExternalTeacher: formData.isExternalTeacher === '是',
				repairMethod: formData.repairMethod || '在线报修',
				isEquipmentChanged: formData.isEquipmentChanged === '是',
				handlingStatus: formData.handlingStatus === '已处理' ? '已处理' : '待处理',
				faultReasonType: formData.faultReasonType,
				faultReason: formData.faultReason
			}

			// 调用API
			const response = await repairAPI.submitRepair(apiData)
			
			// 隐藏加载提示
			uni.hideLoading()


			// 显示成功提示
			uni.showToast({
				title: '提交成功',
				icon: 'success'
			})

			// 向父组件发送提交事件
			emit('submit', apiData)

			// 重置表单
			resetForm()

		} catch (error) {
			// 隐藏加载提示
			uni.hideLoading()
			
			console.error('提交失败:', error)
			uni.showToast({
				title: error.message || '提交失败，请重试',
				icon: 'none'
			})
		}
	}

	// 重置表单
	const resetForm = () => {
		Object.keys(formData).forEach(key => {
			formData[key] = ''
		})
		departmentIndex.value = 0
		repairTypeIndex.value = 0
		repairMethodIndex.value = 0
		formFaultReasonIndex.value = 0

		// 重新初始化默认值
		initTodayDate()
	}

	// 设置报修人的方法（供父组件调用）
	const setReporter = (teacherName) => {
		if (teacherName) {
			formData.reporter = teacherName
		}
	}

	// 暴露方法给父组件
	defineExpose({
		setReporter
	})

	// 组件挂载时初始化默认值
	onMounted(() => {
		initTodayDate()
	})
</script>

<style lang="scss" scoped>
	.form-section {
		position: relative;
	}

	.imgBox {
		position: absolute;
		top: -20rpx;
		right: 20rpx;
		height: 100rpx;
		width: 500rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		padding-left: 10rpx;
		border-left: 6rpx solid #007aff;
	}

	.form-section {
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.form-content {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex-direction: row;
		margin-bottom: 20rpx;

		.label {
			width: 160rpx;
			font-size: 28rpx;
			color: #333;
			flex-shrink: 0;
		}

		.input-field {
			flex: 1;
			height: 70rpx;
			padding: 0 20rpx;
			border: 2rpx solid #e0e0e0;
			border-radius: 8rpx;
			font-size: 28rpx;

			&:focus {
				border-color: #007aff;
				background: white;
			}
		}

		.textarea-field {
			flex: 1;
			height: 110rpx;
			padding: 10rpx;
			border: 2rpx solid #e0e0e0;
			border-radius: 8rpx;
			font-size: 28rpx;
			background: #fafafa;

			&:focus {
				border-color: #007aff;
				background: white;
			}
		}

		.date-picker,
		.picker-view {
			flex: 1;
			height: 70rpx;
			padding: 0 20rpx;
			border: 2rpx solid #e0e0e0;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.arrow {
				margin-left: 20rpx;
				color: #999;
				font-size: 15rpx;
			}
		}

		.radio-item {
			display: inline-flex;
			align-items: center;

			text {
				margin-left: 10rpx;
				font-size: 28rpx;
			}
		}

		.radio-item-first {
			margin-right: 30rpx;
		}
	}

	.submit-btn {
		width: 100%;
		height: 80rpx;
		background: linear-gradient(135deg, #00d4aa 0%, #00b4d8 50%, #0077b6 100%);
		background-size: 200% 200%;
		color: white;
		border: none;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 20rpx rgba(0, 180, 216, 0.4), 
		           inset 0 2rpx 4rpx rgba(255, 255, 255, 0.2),
		           0 0 20rpx rgba(0, 180, 216, 0.2);
		font-size: 32rpx;
		font-weight: bold;
		margin-top: 40rpx;
		letter-spacing: 1rpx;
		position: relative;
		overflow: hidden;
		transition: all 0.3s ease;
		animation: gradientShift 4s ease-in-out infinite, buttonPulse 2s ease-in-out infinite;
		text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
		
		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: -100%;
			width: 100%;
			height: 100%;
			background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
			transition: left 0.5s ease;
		}
		
		&::after {
			content: '';
			position: absolute;
			top: 50%;
			left: 50%;
			width: 0;
			height: 0;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, transparent 70%);
			border-radius: 50%;
			transform: translate(-50%, -50%);
			transition: all 0.3s ease;
		}
		
		&:hover {
			transform: translateY(-2rpx) scale(1.05);
			box-shadow: 0 12rpx 28rpx rgba(0, 180, 216, 0.5), 
			           inset 0 2rpx 4rpx rgba(255, 255, 255, 0.3),
			           0 0 30rpx rgba(0, 180, 216, 0.3);
			
			&::before {
				left: 100%;
			}
			
			&::after {
				width: 100rpx;
				height: 100rpx;
			}
		}

		&:active {
			transform: translateY(1rpx) scale(0.98);
			box-shadow: 0 4rpx 12rpx rgba(0, 180, 216, 0.3);
		}
	}

	.popup-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: flex-end;
		z-index: 1000;
	}

	.date-picker-popup {
		background: white;
		border-radius: 20rpx 20rpx 0 0;
		padding: 20rpx;
		width: 100%;
		max-height: 60vh;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 2rpx solid #f0f0f0;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.cancel-btn,
		.confirm-btn {
			font-size: 28rpx;
			color: #007aff;
			padding: 10rpx 20rpx;
		}
	}

	.picker-view {
		height: 400rpx;
		margin-top: 20rpx;
	}

	.picker-item {
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #333;
	}

	/* 按钮动画效果 */
	@keyframes gradientShift {
		0%, 100% {
			background-position: 0% 50%;
		}
		50% {
			background-position: 100% 50%;
		}
	}

	@keyframes buttonPulse {
		0%, 100% {
			transform: scale(1);
		}
		50% {
			transform: scale(1.02);
		}
	}
</style>